package com.shenhao.hpfa.util;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * JSON片段重组器
 * 用于处理分片发送的JSON报文
 */
@Slf4j
public class JsonFragmentReassembler {
    
    // 存储每个连接的JSON片段缓冲区
    private static final ConcurrentMap<String, StringBuilder> fragmentBuffers = new ConcurrentHashMap<>();
    
    // 存储每个连接的JSON括号计数
    private static final ConcurrentMap<String, Integer> bracketCounters = new ConcurrentHashMap<>();
    
    /**
     * 处理接收到的JSON片段
     * @param channelId 通道ID
     * @param fragment JSON片段
     * @return 完整的JSON字符串列表，如果还未完整则返回空列表
     */
    public static List<String> processFragment(String channelId, String fragment) {
        StringBuilder buffer = fragmentBuffers.computeIfAbsent(channelId, k -> new StringBuilder());
        Integer bracketCount = bracketCounters.computeIfAbsent(channelId, k -> 0);
        
        // 添加片段到缓冲区
        buffer.append(fragment);
        
        String bufferContent = buffer.toString();
        List<String> completeJsons = new ArrayList<>();
        
        // 尝试提取完整的JSON对象
        int startIndex = 0;
        int currentBracketCount = 0;
        boolean inString = false;
        boolean escaped = false;
        
        for (int i = 0; i < bufferContent.length(); i++) {
            char c = bufferContent.charAt(i);
            
            if (escaped) {
                escaped = false;
                continue;
            }
            
            if (c == '\\') {
                escaped = true;
                continue;
            }
            
            if (c == '"' && !escaped) {
                inString = !inString;
                continue;
            }
            
            if (!inString) {
                if (c == '{' || c == '[') {
                    if (currentBracketCount == 0) {
                        startIndex = i;
                    }
                    currentBracketCount++;
                } else if (c == '}' || c == ']') {
                    currentBracketCount--;
                    
                    // 找到一个完整的JSON对象
                    if (currentBracketCount == 0) {
                        String completeJson = bufferContent.substring(startIndex, i + 1);
                        completeJsons.add(completeJson);
                        log.debug("提取到完整JSON，通道: {}, 长度: {}", channelId, completeJson.length());
                    }
                }
            }
        }
        
        // 如果有完整的JSON，更新缓冲区
        if (!completeJsons.isEmpty()) {
            int lastCompleteEnd = bufferContent.lastIndexOf(completeJsons.get(completeJsons.size() - 1)) 
                                + completeJsons.get(completeJsons.size() - 1).length();
            
            // 保留未完成的部分
            String remainingFragment = bufferContent.substring(lastCompleteEnd);
            buffer.setLength(0);
            buffer.append(remainingFragment);
            
            // 更新括号计数
            int newBracketCount = countBrackets(remainingFragment);
            bracketCounters.put(channelId, newBracketCount);
            
            log.debug("JSON片段处理完成，通道: {}, 提取到 {} 个完整JSON，剩余长度: {}", 
                     channelId, completeJsons.size(), remainingFragment.length());
        } else {
            // 更新括号计数
            int newBracketCount = countBrackets(bufferContent);
            bracketCounters.put(channelId, newBracketCount);
            
            log.debug("JSON片段接收，通道: {}, 当前长度: {}, 括号计数: {}", 
                     channelId, bufferContent.length(), newBracketCount);
        }
        
        return completeJsons;
    }
    
    /**
     * 计算JSON字符串中的括号平衡
     * @param json JSON字符串
     * @return 括号平衡计数（0表示平衡）
     */
    private static int countBrackets(String json) {
        int count = 0;
        boolean inString = false;
        boolean escaped = false;
        
        for (char c : json.toCharArray()) {
            if (escaped) {
                escaped = false;
                continue;
            }
            
            if (c == '\\') {
                escaped = true;
                continue;
            }
            
            if (c == '"' && !escaped) {
                inString = !inString;
                continue;
            }
            
            if (!inString) {
                if (c == '{' || c == '[') {
                    count++;
                } else if (c == '}' || c == ']') {
                    count--;
                }
            }
        }
        
        return count;
    }
    
    /**
     * 清理指定通道的缓冲区
     * @param channelId 通道ID
     */
    public static void clearBuffer(String channelId) {
        fragmentBuffers.remove(channelId);
        bracketCounters.remove(channelId);
        log.debug("清理JSON片段缓冲区，通道: {}", channelId);
    }
    
    /**
     * 清理所有缓冲区
     */
    public static void clearAllBuffers() {
        fragmentBuffers.clear();
        bracketCounters.clear();
        log.debug("清理所有JSON片段缓冲区");
    }
} 